package cc.jq1024.trigger.job;

import cc.jq1024.domain.task.model.entity.TaskEntity;
import cc.jq1024.domain.task.service.ITaskService;
import cc.jq1024.router.strategy.IDBRouterStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: jia-qiang ljq1024.cc
 * @desc: 发送MQ消息任务队列
 * @Date: 2024-06-20-21:06
 */
@Slf4j
@Component()
public class SendMessageTaskJob {
    @Resource
    private ITaskService taskService;
    @Resource
    private IDBRouterStrategy dbRouter;

    @Scheduled(cron = "0/5 * * * * ?")
    public void exec_db01() {
        try {
            // 设置库表
            dbRouter.setDBKey(1);
            dbRouter.setTBKey(0);
            // 查询未发送的任务
            List<TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList();
            if (taskEntities.isEmpty()) return;
            // 发送MQ消息
            for (TaskEntity taskEntity : taskEntities) {
                try {
                    taskService.sendMessage(taskEntity);
                    taskService.updateTaskSendMessageCompleted(taskEntity.getUserId(), taskEntity.getMessageId());
                } catch (Exception e) {
                    log.error("定时任务,发送MQ消息失败 userId: {} topic: {}", taskEntity.getUserId(), taskEntity.getTopic());
                    taskService.updateTaskSendMessageFail(taskEntity.getUserId(), taskEntity.getMessageId());
                }
            }
        } catch (Exception e) {
            log.error("定时任务，扫描MQ任务表发送消息失败。", e);
        } finally {
            dbRouter.clear();
        }
    }

    @Scheduled(cron = "0/5 * * * * ?")
    public void exec_db02() {
        try {
            // 设置库表
            dbRouter.setDBKey(2);
            dbRouter.setTBKey(0);
            // 查询未发送的任务
            List<TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList();
            if (taskEntities.isEmpty()) return;
            // 发送MQ消息
            for (TaskEntity taskEntity : taskEntities) {
                try {
                    taskService.sendMessage(taskEntity);
                    taskService.updateTaskSendMessageCompleted(taskEntity.getUserId(), taskEntity.getMessageId());
                } catch (Exception e) {
                    log.error("定时任务，发送MQ消息失败 userId: {} topic: {}", taskEntity.getUserId(), taskEntity.getTopic());
                    taskService.updateTaskSendMessageFail(taskEntity.getUserId(), taskEntity.getMessageId());
                }
            }
        } catch (Exception e) {
            log.error("定时任务，扫描MQ任务表发送消息失败。", e);
        } finally {
            dbRouter.clear();
        }
    }


//    @Scheduled(cron = "0/5 * * * * ?")
//    public void exec() {
//        try {
//            // 获取分库数量
//            int dbCount = dbRouter.dbCount();
//
//            // 逐个库扫描表【每个库一个任务表】
//            for (int dbIndex = 1; dbIndex <= dbCount; dbIndex++) {
//                int finalDbIndex = dbIndex;
//                executor.execute(() -> {
//                    try {
//                        dbRouter.setDBKey(finalDbIndex); // 设置查询某个库 0库？1库？2库？
//                        dbRouter.setTBKey(0); //  设置查询某个表 0表？1表？2表？
//                        List<TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList();
//                        if (taskEntities.isEmpty()) return;
//                        // 发送MQ消息
//                        for (TaskEntity taskEntity : taskEntities) {
//                            // 开启线程发送，提高发送效率。配置的线程池策略为 CallerRunsPolicy，
//                            // 在 ThreadPoolConfig 配置中有4个策略，面试中容易对比提问。可以检索下相关资料。
//                            executor.execute(() -> {
//                                try {
//                                    taskService.sendMessage(taskEntity);
//                                    taskService.updateTaskSendMessageCompleted(taskEntity.getUserId(), taskEntity.getMessageId());
//                                } catch (Exception e) {
//                                    log.error("定时任务，发送MQ消息失败 userId: {} topic: {}", taskEntity.getUserId(), taskEntity.getTopic());
//                                    taskService.updateTaskSendMessageFail(taskEntity.getUserId(), taskEntity.getMessageId());
//                                }
//                            });
//                        }
//                    } finally {
//                        dbRouter.clear();
//                    }
//                });
//            }
//        } catch (Exception e) {
//            log.error("定时任务，扫描MQ任务表发送消息失败。", e);
//        } finally {
//            dbRouter.clear();
//        }
//    }
}
